<script setup lang="ts">
import { NSpin, NSkeleton } from "naive-ui";
import { IDraw } from "./";
import { defineProps, onMounted, onUnmounted, ref, toRef, watch } from "vue";
import { useLoading } from "../vue/use";

interface IPorps {
  draw: IDraw;
  height?: string;
  loading?: boolean;
}

const props = defineProps<IPorps>();
const propsLoading = toRef(props, "loading");

// 根据输入参数计算组件高度
const height = props.height ? props.height : "50vh";
const style: Partial<CSSStyleDeclaration> = {
  height,
};

const initDraw = () => {
  props.draw.beforeInit();
  props.draw.init(draw.value);
  props.draw.afterInit();
  props.draw.logger(`初始化 画图区域`);
};

// 等待挂载
const { loading, delayLoadingClose } = useLoading();
const draw = ref<any>(null);
watch(draw, () => {
  if (draw.value !== null) {
    initDraw();
    props.draw.logger("画图了");
  }
});

onMounted(() => {
  delayLoadingClose();
});

// 未挂载时销毁
onUnmounted(() => {
  props.draw.dispose();
});
</script>

<template>
  <div>
    <NSpin
      v-if="loading || propsLoading"
      :show="loading || propsLoading"
      :style="style"
    >
      <NSkeleton class="tw-h-full"></NSkeleton>
    </NSpin>
    <div v-else class="tw-border" :style="style" ref="draw"></div>
  </div>
</template>

<style scoped></style>
